<template>
  <el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center" lock-scroll width="900px" append-to-body>
    <el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules" v-loading="loading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker v-model="dataForm.startDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="timestamp"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="endDate">
            <el-date-picker v-model="dataForm.endDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="timestamp"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="应收金额" prop="receivable">
            <el-input v-model="dataForm.receivable" @blur="hanldBlurReceivalbeOrActual" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额" prop="actual">
            <el-input v-model="dataForm.actual" @change="hanldBlurReceivalbeOrActual" :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="支付情况" prop="isPayed">
            <el-radio-group v-model="dataForm.isPayed" required :style="{}">
              <el-radio v-for="(item, index) in isPayedOptions" :key="index" :label="item.enCode">{{ item.fullName }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="加盟政策" prop="policy">
            <el-input v-model="dataForm.policy" placeholder="请输入" show-word-limit :style="{ width: '100%' }" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否发送邮件" prop="emailCC">
            <el-checkbox v-model="dataForm.isEmail"></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="收件人" prop="emailTo">
            <org-select ref="user-org" buttonType="button" v-model="dataForm.emailTo" title="添加用户" class="mb-10" @change="onOrgChange" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import OrgSelect from '@/components/Process/OrgSelect'
export default {
  components: { OrgSelect },
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        id: '',
        isPayed: 'No',
        campusId: undefined,
        startDate: undefined,
        endDate: undefined,
        receivable: undefined,
        actual: undefined,
        policy: undefined,
        createUserId: undefined,
        createTime: undefined,
        isEmail: false,
        emailTo: [],
        emailCC: undefined
      },
      rules: {
        campusId: [
          {
            required: true,
            message: '请输入校区',
            trigger: 'change'
          }
        ],
        startDate: [
          {
            required: true,
            message: '请选择服务开始日期',
            trigger: 'change'
          }
        ],
        endDate: [
          {
            required: true,
            message: '请选择服务截止日期',
            trigger: 'change'
          }
        ],
        receivable: [
          {
            required: true,
            message: '请输入应收金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        actual: [
          {
            required: true,
            message: '请输入应收金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        emailTo: [
          {
            required: true,
            message: '请选择邮件的收件人',
            trigger: 'change'
          }
        ]
      },
      isPayedOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getisPayedOptions()
  },
  mounted() {},
  methods: {
    getisPayedOptions() {
      getDictionaryDataSelector('PayStatus').then(res => {
        this.isPayedOptions = res.data.list.filter(o => o.enCode != 'PartialNo' && o.enCode != 'Refunded' && o.enCode != 'No')
      })
    },
    onOrgChange(data) {
      this.dataForm.emailTo = data
    },
    goBack() {
      this.$emit('refresh')
    },
    init(id, isDetail) {
      this.dataForm.id = id || ''
      this.visible = true
      this.isDetail = isDetail || false
      this.loading = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        request({
          url: `api/campus/contract/${this.dataForm.id}`,
          method: 'get'
        }).then(res => {
          this.dataForm = res.data
        })

        this.loading = false
      })
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (index === 1) {
          sums[index] = ''
          return
        }
        if (index === 3) {
          sums[index] = ''
          return
        }
        if (index === 4) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              this.dataForm.actual = prev + curr
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 元'
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },
    hanldBlurReceivalbeOrActual() {
      if (this.dataForm.receivable == this.dataForm.actual) {
        this.dataForm.isPayed = 'Yes'
      } else if (this.dataForm.actual == 0) {
        this.dataForm.isPayed = 'No'
      } else if (this.dataForm.receivable > this.dataForm.actual) {
        this.dataForm.isPayed = 'PartialYes'
      } else {
        this.$message({
          message: '请再次确认实收金额，如无误请忽略。',
          type: 'warning',
          duration: 3000
        })
      }
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.dataForm.id) {
            request({
              url: `/api/campus/contract/${this.dataForm.id}`,
              method: 'put',
              data: this.dataForm
            }).then(res => {
              this.loading = false
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  ;(this.visible = false), this.$emit('refresh', true)
                }
              })
            })
          }
        }
      })
    }
  }
}
</script>
